<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>异步</title>

    <style type="text/css"></style>
  </head>
  <body>
    <div>
      <div>
        <button id="btn1">点击变大</button>
        <button id="btn2">点击延迟变大</button>
        <button id="btn3">发起XHR请求或者背景图像，并设置为背景</button>
        <button id="btn4">接口请求获取文章数据</button>
      </div>
      <article id="article"></article>
    </div>
  </body>
  <script>
    let btn1 = document.getElementById("btn1");
    let btn2 = document.getElementById("btn2");
    let btn3 = document.getElementById("btn3");
    let btn4 = document.getElementById("btn4");
    let body = document.querySelector("body");
    let article = document.getElementById("article");
    btn1.onclick = function () {
      changeSize(this, 1);
    };

    btn2.onclick = function () {
      let this_ = this;
      // 手动阻塞1s
      setTimeout(() => {
        changeSize(this_, 2);
      }, 1000);
    };

    btn3.onclick = function () {
      loadAsset("img/background.jpg", "blob", displayImage);
    };

    btn4.onclick = function () {
      loadArticle();
    };

    // 异步callbacks 回调函数
    function loadAsset(url, type, callback) {
      // 创建XHR请求实例
      let xhr = new XMLHttpRequest();

      // 设置URL地址和请求方法
      xhr.open("GET", url);

      // 设置返回数据类型
      xhr.responseType = type;

      // 等待请求执行完成执行callback函数
      xhr.onload = function () {
        callback(xhr.response);
      };

      // 发送请求
      xhr.send();
    }

    // 显示图片
    function displayImage(blob) {
      let imageURL = URL.createObjectURL(blob);
      body.background = imageURL;
    }

    // 异步promises
    function loadArticle() {
      fetch("https://www.daived.com/api/front/blog/article/query/one?id=18")
        .then(function (response) {
          return response.json();
        })
        .then(function (json) {
          console.log(json);
          article.textContent = json.data.title;
        })
        .catch(function (error) {
          console.error(error.message);
        });
    }

    // 改变大小
    function changeSize(elem, num) {
      if (elem.tag == 1 || elem.tag == null) {
        elem.style.width = "200px";
        elem.style.height = "200px";
        switch (num) {
          case 1:
            elem.textContent = "点击变小";
            break;
          case 2:
            elem.textContent = "点击延迟变小";
            break;
        }
        elem.tag = 2;
      } else {
        elem.style.width = "auto";
        elem.style.height = "auto";
        switch (num) {
          case 1:
            elem.textContent = "点击变大";
            break;
          case 2:
            elem.textContent = "点击延迟变大";
            break;
        }
        elem.tag = 1;
      }
    }
  </script>
</html>
